package com.jl.security;

import java.security.SecureRandom;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.annotations.JSStaticFunction;

import com.jl.js.core.ByteArray;

public class Crypto extends ScriptableObject {

	static {
		java.security.Security.addProvider(new BouncyCastleProvider());
	}

	private final static ByteArray defaultIV = new ByteArray(new byte[8]);

	@JSStaticFunction
	public static void init() {
	};

	@JSStaticFunction
	public static byte[] encrypt(String name, ByteArray key, ByteArray data,
			ByteArray iv) {
		if (iv == null || iv.length() == 0) {
			iv = defaultIV;
		}
		return MyCipher.encrypt(name, key.getBytes(), data.getBytes(),
				iv.getBytes());
	}

	@JSStaticFunction
	public static byte[] decrypt(String name, ByteArray key, ByteArray data,
			ByteArray iv) {
		if (iv == null || iv.length() == 0) {
			iv = defaultIV;
		}
		return MyCipher.decrypt(name, key.getBytes(), data.getBytes(),
				iv.getBytes());
	}

	@JSStaticFunction
	public static byte[] sign(String name, ByteArray key, ByteArray data,
			ByteArray iv) {
		if (iv == null || iv.length() == 0) {
			iv = defaultIV;
		}
		return Mac.sign(name, key.getBytes(), data.getBytes(), iv.getBytes());
	}

	@JSStaticFunction
	public static boolean verify(ByteArray exp, String name, ByteArray key,
			ByteArray data, ByteArray iv) {
		if (iv == null || iv.length() == 0) {
			iv = defaultIV;
		}
		return Mac.verify(exp.getBytes(), name, key.getBytes(),
				data.getBytes(), iv.getBytes());
	}

	@JSStaticFunction
	public static byte[] checksum(String name, ByteArray value, int baseValue) {
		return Checksum.checksum(name, value.getBytes(), 0, value.length(),
				baseValue);
	}

	@JSStaticFunction
	public static byte[] derive(String name, ByteArray key, ByteArray data) {
		return Disperse.disperse(name, key.getBytes(), data.getBytes());
	}

	@JSStaticFunction
	public static byte[] digest(String name, ByteArray data) {
		return Digest.digest(name, data.getBytes(), 0, data.length());
	}

	@JSStaticFunction
	public static byte[] random(int length) {
		SecureRandom sr = new SecureRandom();
		byte[] random = new byte[length];
		sr.nextBytes(random);
		return random;
	}

	@Override
	public String getClassName() {
		return "Crypto";
	}

}
